import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { addTab } from '@/utils/utils';
import { DatePicker, Form, Space } from 'antd';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Table,
    Button,
    Card,
    Col,
    Input,
    Row,
    Select,
    Tooltip,
    Modal,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { pathname } = window.location;
const { RangePicker } = DatePicker;

const events = {
    deliver: '投递',
    pickup: '取件',
    retrieve: '取回',
    problem_handle: '问题件',
};

const errers = {
    1: 'api错误',
    2: '接口返回失败',
    3: '接口异常',
    4: '无需同步',
    5: '第三方接口异常',
};

const status = {
    1: '成功',
    2: '失败',
};

const FormItem = Form.Item;
const { Option } = Select;

interface LogListProps extends FormComponentProps {
    dispatch: Dispatch<any>;
    logisCenterLogList: any;
    INITINFO: any;
    loading: boolean;
}

interface LogListState {
    push_visible: boolean;
    formValues: any;
    rowId: number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
    logisCenterLogList,
    common: { INITINFO },
    loading,
}: any) => ({
    logisCenterLogList,
    INITINFO,
    loading: loading.effects['logisCenterLogList/fetch'],
}))
class LogList extends React.Component<LogListProps, LogListState> {
    columns: any = [
        {
            title: '快递公司',
            dataIndex: 'expressName',
            render: (text: any, record: any) => (
                <Tooltip title={text}>
                    <div
                        className="nameLink"
                        onClick={() => this.handleShowBatch(record.id, record.expressId, record.expCode)}
                    >
                        {text || '--'}
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '运单号',
            dataIndex: 'expCode',
            render: (text: any) => (
                <Tooltip title={text}>
                    <div className="wordOmit">
                        {text}
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '事件类型',
            dataIndex: 'event',
            render: (text: string, record: any) => <span>{`${events[text]}${!record.reSync ? '' : `（第${record.reSync}次补偿推送）`}`}</span>,
        },
        {
            title: '错误类型',
            dataIndex: 'errorType',
            render: (text: string) => errers[text] || '--',
        },
        {
            title: '失败原因',
            dataIndex: 'faildReason',
            render: (text: string) => text || '--',
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (text: string) => status[text],
        },
        {
            title: '推送时间',
            dataIndex: 'pushTime',
        },
        {
            title: '操作',
            dataIndex: 'id',
            render: (id: any, record: any) => (
                <span
                    className="operLink"
                    onClick={() => this.handleShowBatch(id, record.expressId, record.expCode)}
                >
                    详情
                </span>
            ),
        },
    ];

    state: LogListState = {
        push_visible: false,
        formValues: {},
        rowId: 0,
    };

    static getDerivedStateFromProps(props: any, state: any) {
        const { search } = props.location;
        const query = qs.parse(search, { ignoreQueryPrefix: true });
        const { ...formValues } = query;
        return {
            ...state,
            formValues,
        };
    }

    componentDidMount() {
        // this.setFieldsValue();
        this.fetchExpressList();
    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const { formValues } = this.state;
        if (!_.isEqual(formValues, prevState.formValues)) {
            // this.setFieldsValue();
            this.fetchLogList();
        }
    }

    // 设置表单值
    // setFieldsValue = () => {
    //     const { formValues } = this.state;
    //     const { form: { setFieldsValue } } = this.props;
    //     setFieldsValue(formValues);
    // }

    // 获取快递公司列表
    fetchExpressList = () => {
        const { dispatch } = this.props;
        dispatch({ type: 'common/fetchExpressList' });
    }

    // 获取数据
    fetchLogList = () => {
        const { formValues } = this.state;
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterLogList/fetch',
            payload: formValues,
        });
    }

    /**
     * 查询
     */
    handleSearch = (values: any) => {

        // const { form: { validateFields } } = this.props;
        // validateFields((err, values) => {
        //     if (err) return;

        const { formValues: currentQuery } = this.state;
        const realQuery = _.pick(values, Object.keys(values).filter((key: string) => values[key]));
        const realCurrentQuery = _.pick(currentQuery,
            Object.keys(currentQuery).filter((key: string) => currentQuery[key]));
        if (_.isEqual(realQuery, realCurrentQuery)) {
            this.fetchLogList();
        } else {
            const { dispatch } = this.props;
            addTab(dispatch, {
                name: '日志查询',
                url: `${pathname}?${qs.stringify(values)}`,
                isTopMenu: true,
            });
        }
        // });
    };

    /**
     * 重置
     */
    handleReset = () => {
        const { form: { resetFields } } = this.props;
        resetFields();

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '日志查询',
            url: pathname,
            isTopMenu: true,
        });
    };

    /**
     * 查看详情
     */
    handleShowBatch = (id: number, expressId: number, expCode: string) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '查看日志',
            url: `${pathname}/detail?id=${id}&expressId=${expressId}&expCode=${expCode}`,
        });
    };

    onClickRow = ({ id }: any) => ({
        onClick: () => {
            this.setState({ rowId: id });
        },
    })

    setRowClassName = ({ id }: any) => {
        const { rowId } = this.state;
        return id === rowId ? 'clickRowStyl' : '';
    }

    // 渲染查询表单
    renderSearchFormElem = () => {
        const {
            INITINFO: { expressList },
        } = this.props;

        return (
            <Form onFinish={this.handleSearch} className="tableListForm">
                <Row gutter={12}>
                    <Col md={6} sm={24}>
                        <FormItem label="快递公司" name="expressId" colon={false}>
                            <Select
                                showSearch
                                allowClear
                                placeholder="请选择"
                                filterOption={(input: any, option: any) => (
                                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                )}
                            >
                                {expressList.map((item: any) => (
                                    <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                                ))}
                            </Select>
                            {/* {getFieldDecorator('expressId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    filterOption={(input: any, option: any) => (
                                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    )}
                                >
                                    {expressList.map((item: any) => (
                                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                                    ))}
                                </Select>,
                            )} */}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="快递单号" name="expCode" colon={false}>
                            {/* {getFieldDecorator('expCode')(
                                <Input
                                    allowClear
                                    placeholder="请输入"
                                    style={{ width: '100%' }}
                                />,
                            )} */}
                            <Input
                                allowClear
                                placeholder="请输入"
                                style={{ width: '100%' }}
                            />
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="事件类型" name="event" colon={false}>
                            <Select
                                allowClear
                                placeholder="请选择"
                            >
                                {
                                    Object.keys(events).map((event: any) => (
                                        <Option key={event} value={event}>{events[event]}</Option>
                                    ))
                                }
                            </Select>
                            {/* {getFieldDecorator('event')(
                                <Select
                                    allowClear
                                    placeholder="请选择"
                                >
                                    {
                                        Object.keys(events).map((event: any) => (
                                            <Option key={event} value={event}>{events[event]}</Option>
                                        ))
                                    }
                                </Select>,
                            )} */}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <div className="flexFeView">
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="smallButton"
                            >
                                查询
                            </Button>
                            <Button
                                type="primary"
                                className="addButton smallButton marginL16"
                                onClick={this.handleReset}
                            >
                                重置
                            </Button>
                        </div>
                    </Col>
                </Row>
            </Form>
        );
    }

    onFinish = (values: any) => {
        const { push_time, ...n_values } = values;

        const params = {
            ...n_values,
            startTime: moment(push_time[0]).format('YYYY-MM-DD HH:mm:ss'),
            endTime: moment(push_time[1]).format('YYYY-MM-DD HH:mm:ss'),
        };
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterLogList/fetchPush',
            payload: params,
        });

        this.setState({ push_visible: false });
    }

    // 渲染补录弹窗
    renderPushModalElem = () => {

        const { push_visible } = this.state,
            {
                INITINFO: { expressList },
            } = this.props;;

        return (
            <Modal
                title="消息补推"
                visible={push_visible}
                onCancel={() => {
                    this.setState({
                        push_visible: false,
                    });
                }}
                footer={null}
                destroyOnClose={true}
            >
                <Form
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    onFinish={this.onFinish}
                >
                    <Form.Item label="快递公司" name="expressId" colon={false} rules={[
                        {
                            required: true,
                            message: '请选择快递公司'
                        }
                    ]} >
                        <Select
                            showSearch
                            allowClear
                            placeholder="请选择"
                            filterOption={(input: any, option: any) => (
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            )}
                        >
                            {expressList.map((item: any) => (
                                <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <FormItem label="快递单号" name="expCode" colon={false} rules={[
                        {
                            required: true,
                        }
                    ]}>
                        <Input
                            allowClear
                            placeholder="请输入"
                            style={{ width: '100%' }}
                        />
                    </FormItem>
                    <FormItem label="事件类型" name="event" colon={false} rules={[
                        {
                            required: true,
                            message: '请选择事件类型'
                        }
                    ]}>
                        <Select
                            allowClear
                            placeholder="请选择"
                        >
                            {
                                Object.keys(events).map((event: any) => (
                                    <Option key={event} value={event}>{events[event]}</Option>
                                ))
                            }
                        </Select>
                    </FormItem>
                    <FormItem label="推送时间" name="push_time" colon={false} rules={[
                        {
                            required: true,
                            message: '请选择推送时间'
                        }
                    ]}>
                        <RangePicker showTime />
                    </FormItem>
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Space size="middle">
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                            <Button type="primary" danger onClick={() => {
                                this.setState({
                                    push_visible: false,
                                });
                            }} >
                                取消
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        );
    }

    render() {
        const { logisCenterLogList: { data }, loading } = this.props;

        return (
            <>
                <PageHeader />

                <Card bordered={false} className="searchForm">
                    {this.renderSearchFormElem()}
                </Card>

                <Card bordered={false} className="tableList">
                    <div style={{ paddingLeft: 20, display: 'flex', alignItems: 'center' }}>
                        <Button type="primary" onClick={() => {
                            this.setState({ push_visible: true });
                        }}>数据补录</Button>
                        <div style={{ paddingLeft: 20, color: 'red' }}>未开启数据对接配置的订单将无法查询！！！</div>
                    </div>
                    <Table
                        rowKey="id"
                        className="statementTable tableHeight60"
                        columns={this.columns}
                        dataSource={data.list || []}
                        pagination={false}
                        loading={loading}
                        onRow={this.onClickRow}
                        rowClassName={this.setRowClassName}
                    />
                </Card>
                {this.renderPushModalElem()}
            </>
        );
    }
}

export default LogList;
